<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarResource;

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\AuctionOrder\Transfer;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\Finance\CarOwnerCompensate;
use AuctionCore\Finance\ReceivableRefund;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\Account\Back\Employee;
use AuctionBack\Logic\RefundLogic;

/**
 * 自收车辆
 *
 * @author Xmh
 */
class SelfReceiveCar
{
    private $SelfReceiveCarModel = null;
    private $CarOwnerCompensate = null;
    private $ReceivableRefund = null;

    public function __construct()
    {
        $this->SelfReceiveCarModel = M('self_receive_car');
        $this->CarOwnerCompensate = new CarOwnerCompensate();
        $this->ReceivableRefund = new ReceivableRefund();
    }

    /**
     * 新增自收车辆
     *
     * @param $data
     *
     * @return mixed
     */
    public static function create($data)
    {
        if ($data['car_id'] < 1) {
            return false;
        }
        if ($data['sid'] < 1) {
            $data['sid'] = M("cars")->where(['car_id' => $data['car_id']])->getField("sid");
        }
        //获取第一次自收时间
        $latest = M("self_receive_car")->where(['sid' => $data['sid']])->find();
        if (!empty($latest)) {
            $data['createtime'] = $latest['createtime'];
        } else {
            $data['createtime'] = date("Y-m-d H:i:s");
        }
        $res = M('self_receive_car')->add($data);
        return $res;
    }


    /**
     * @param       $page
     * @param       $limit
     * @param array $params
     *
     * @return array
     */
    public function get_self_receive_car_list($page, $limit, $params = [])
    {
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $map = [];
        $map['src.status'] = intval($params['status']);
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['in', $params['location_area']];
        }
        //付款状态
        $pay_status = $params['pay_status'];
        if ($pay_status == 2) {
            $map['_string'] = 'c.pay_status = 2 OR (c.pay_status = 3 AND c.three_in_one = 2)';
        } elseif ($pay_status == 1) {
            $map['c.pay_status'] = ['eq', $pay_status];
        }
        //车辆编号
        if (!empty($params['sno'])) {
            $map['c.sno'] = ['LIKE', '%' . $params['sno'] . '%'];
        }

        if (!empty($params['self_type'])) {
            $map['src.self_type'] = ['eq', $params['self_type']];
        }

        if ($map['src.status'] == 3) {
            $map['o.is_other_channel_deal'] = ['eq', 0];
        }

        $cols = "c.car_id,c.car_no,c.sno,c.location_area,c.brand_id,c.series_id,c.model_id,c.plate_prefix,c.plate_suffix
            ,c.pay_status,c.car_source,c.three_in_one,c.first_money,c.tail_money,c.composite_state,c.accident_level
            ,src.src_id,src.status,src.dealtime,src.createtime as self_receive_time,src.dealer_name,src.dealer_phone
            ,o.success_dealer_id,o.order_id";
        $order = 'src.createtime DESC';
        $prefix = C("DB_PREFIX");

        $total = $this->SelfReceiveCarModel->alias('src')
            ->join($prefix . "order as o ON o.order_id = src.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->where($map)->count();

        $list = $this->SelfReceiveCarModel->alias('src')->field($cols)
            ->join($prefix . "order as o ON o.order_id = src.order_id")
            ->join($prefix . "cars as c ON c.car_id = o.car_id")
            ->where($map)->order($order)->page($page)->limit($limit)->select();

        if (!empty($list)) {
            $cm = new CarModel();
            $address = new Address();
            foreach ($list as $key => $val) {
                //车型
                $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                $series = $cm->get_model_by_id($val['series_id'], 'series');
                $model = $cm->get_model_by_id($val['model_id']);
                $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name'];
                //所在地
                if ($val['location_area']) {
                    $location_area = $address->get_name_by_code($val['location_area']);
                    $list[$key]['location_area'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
                //车牌号
                $list[$key]['plate_number'] = C("PLATE_PREFIX." . $val['plate_prefix']) . $val['plate_suffix'];
                //车况等级
                $list[$key]['car_level'] = $val['composite_state'] . $val['accident_level'];
                //成交车商信息
                if ($val['status'] == 3) {
                    $dealer = new Dealer($val['success_dealer_id']);
                    $dealerInfo = $dealer->baseInfo();
                    $list[$key]['dealer_contact_person'] = $dealerInfo['contact_person'];
                    $list[$key]['dealer_contact_mobile'] = $dealerInfo['contact_mobile'];
                } elseif ($val['status'] == 4) { //其它渠道
                    $list[$key]['dealer_contact_person'] = $val['dealer_name'];
                    $list[$key]['dealer_contact_mobile'] = $val['dealer_phone'];
                }

                //付款状态
                $pay_status = $val['pay_status'];
                $list[$key]['pay_status_name'] = C('ORDER_PAY_STATUS')[$pay_status];

                if ($val['car_source'] == 1) {
                    $rate = "100%";
                } elseif ($val['car_source'] == 2) {
                    $rate = $val['three_in_one'] == 1 ? '50%' : '0%';
                }
                if ($pay_status == 0) { // 如果未付的就只显示 --，不显示百分比
                    $list[$key]['pay_status'] = $list[$key]['pay_status_name'];
                } else {
                    $list[$key]['pay_status'] = $list[$key]['pay_status_name'] . $rate;
                }

                //交易成功成交时间
                if ($val['status'] == 3) {
                    $transfer_log = Transfer::get_transfer_log(['order_id' => $val['order_id'], 'result' => 2]);
                    $list[$key]['transfer_success_time'] = $transfer_log['createtime'];
                }
            }
        }
        $data = ['total' => $total, 'list' => $list];
        return $data;
    }

    /**
     * 待检测列表
     * @param int $page
     * @param int $size
     * @param array $params
     * @return array
     */
    public function getWaitingCheckList($page, $size, $params)
    {
        $order = 'car_owner.modify_time DESC';
        $map = $this->makeWaitingCheckListParams($params);
        $fields = 'cars.car_id,cars.car_no,cars.sid,cars.sno,cars.plate_prefix,cars.plate_suffix,
                car_owner.*,come_form.from_name';
        $total = M('self_receive_car')->alias('src')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'cars as cars ON src.car_id = cars.car_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'car_owner as car_owner ON cars.car_id = car_owner.old_car_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . "come_from as come_form ON car_owner.comefrom = come_form.from_id")
            ->where($map)->count();

        $list = M('self_receive_car')->alias('src')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'cars as cars ON src.car_id = cars.car_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'car_owner as car_owner ON cars.car_id = car_owner.old_car_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . "come_from as come_form ON car_owner.comefrom = come_form.from_id")
            ->where($map)->limit($size)->page($page)->order($order)
            ->field($fields)
            ->select();
        //echo M()->getLastSql();
        if (!empty($list)) {
            $address = new Address();
            $cm = new CarModel();
            foreach ($list as $key => $val) {
                if ($val['brand_id'] || $val['series_id'] || $val['model_id']) {
                    $brand = $cm->get_model_by_id($val['brand_id'], 'brand');
                    $series = $cm->get_model_by_id($val['series_id'], 'series');
                    $model = $cm->get_model_by_id($val['model_id']);
                    $list[$key]['car_model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['year'] . ' ' . $model['name'];
                } else {
                    $list[$key]['car_model'] = $val['car_model'];
                }

                if ($params['status'] == 6) {
                    $car = Car::get_car_by_owner_id($val['owner_id']);
                    $list[$key]['car_no'] = $car['car_no'];
                }

                if ($val['location_area']) {
                    $location_area = $address->get_name_by_code($val['location_area']);
                    $list[$key]['location_area'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }

                //车牌号
                $list[$key]['plate_number'] = C("PLATE_PREFIX." . $val['plate_prefix']) . $val['plate_suffix'];
                //获取预约地址
                if ($val['service_method'] == 2) {
                    $province = $address->get_name_by_code($val['reserve_province']);
                    $city = $address->get_name_by_code($val['reserve_city']);
                    $area = $address->get_name_by_code($val['reserve_area']);
                    $list[$key]['address'] = $province . " " . $city . " " . $area . " " . $val['reserve_address'];
                } elseif ($val['service_method'] == 3) {
                    //门店
                    $store = new \AuctionCore\Other\Store();
                    $map = array();
                    $map['store_id'] = array('eq', $val['reserve_store']);
                    $stores = $store->detail($map);
                    $list[$key]['address'] = $stores['store_name'];

                } else {
                    $list[$key]['address'] = "未知";
                }
                //转换时间
                $list[$key]['reserve_time'] = transform_date($val['reserve_time']);
                $checker = Employee::user_info_id($val['checker_id']);
                $myserver = Employee::user_info_id($val['service_id']);
                $list[$key]['checker_name'] = $checker['real_name'];
                $list[$key]['checker_user_mobile'] = $checker['mobile'];
                $list[$key]['server_name'] = $myserver['real_name'];
                $list[$key]['phone_has_star'] = showHideMobile($val['phone']);
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 构造查询条件
     * @param array $params 参数
     * @return mixed
     */
    public function makeWaitingCheckListParams($params)
    {
        $map['car_owner.business_status'] = array('elt', 4); //待预约检测
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['car_owner.location_area'] = array('in', $params['location_area']);
        }
        if (!empty($params['pay_status'])) {
            if ($params['pay_status'] == 2) {
                $map['_string'] = 'cars.pay_status = 2 OR (cars.pay_status = 3 AND cars.three_in_one = 2)';
            } elseif ($params['pay_status'] == 1) {
                $map['cars.pay_status'] = ['eq', $params['pay_status']];
            }
        }
        if (!empty($params['sno'])) {
            $map['cars.sno'] = array('eq', $params['sno']);
        }
        $map['car_owner.old_car_id'] = array('neq', '');
        return $map;
    }


    /**
     * 获取自收车辆详情
     *
     * @param int $src_id
     *
     * @return mixed
     */
    public function self_receive_car_detail($src_id)
    {
        if (intval($src_id) < 1) return false;
        $cols = 'src.src_id,src.status,src.remark,src.dealer_name,src.dealer_phone,src.trade_price,src.take_car_man,src.issue_id,
                 src.compensate_type,src.compensate,src.back_method,src.self_type,src.reserve_price as current_reserve_price,
                 src.transfer_fee,src.d_order_id,src.report_type,src.dealtime,
                 o.order_id,o.order_no,o.is_consult,o.success_dealer_id,o.bidding_best_price,o.bid_best_price,o.commision,o.transfer_fee as order_transfer_fee,
                 o.consult_increase,o.success_price,o.reserve_price,o.bidding_end_time,o.is_consult,o.company_subsidies,o.confirm_type,o.trade_time,
                 c.car_id,c.sno,c.brand_id,c.series_id,c.model_id,c.car_color,c.emission,c.plate_prefix,c.pointer_mileage,c.plate_prefix,c.plate_suffix,
                 c.car_color,c.composite_state,c.accident_level,c.car_status,c.three_in_one,c.car_source,c.car_no,c.emission,c.au_times,c.is_self_receive,
                 c.self_receive_dealer_id,
                 c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.transfer_limit,c.location_area,c.pay_status,c.first_money,c.tail_money,c.success_price,
                 c.is_self_receive,c.sid,co.seller_name,co.phone as seller_phone,co.comefrom,co.owner_type,co.contact_person,
                 e.real_name as checker_name,e.mobile as checker_phone,co.owner_id';
        $map = array();
        $map['src.src_id'] = ['eq', $src_id];
        $prefix = C('DB_PREFIX');
        $detail = $this->SelfReceiveCarModel->alias('src')->field($cols)
            ->join($prefix . "order as o ON o.order_id = src.order_id")
            ->join($prefix . "cars as c ON c.car_id = src.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = c.owner_id")
            ->join($prefix . "employee as e ON e.emp_id = co.checker_id")
            ->where($map)
            ->find();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);
        $detail['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $detail['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
        $detail['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
        $detail['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
        $detail['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
        $detail['transfer_limit_str'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
        $channel = \AuctionCore\Other\Channel::get_full_name_by_id($detail['comefrom']);
        $detail['channel_id'] = $detail['comefrom'];
        $detail['comefrom'] = $channel;
        $addr = new \AuctionCore\Other\Address();
        $detail['first_reg_city'] = $addr->get_name_by_code($detail['reg_city']);
        $detail['location_area_code'] = $detail['location_area']; //所在地code
        $detail['location_area'] = $addr->get_name_by_code($detail['location_area']);
        $detail['reau_times'] = $detail['au_times'] - 1;
        if ($detail['trade_time'] == '0000-00-00 00:00:00') {
            $detail['trade_time'] = '';
        }
        $pay_status = $detail['pay_status'];
        if ($pay_status == 1) {           //待付首款
            $detail['pay_status_name'] = "待付首款";
        } elseif ($pay_status == 2) {     //已付首款
            $detail['pay_status_name'] = "已付首款";
        } elseif ($pay_status == 3) {  //待付尾款
            $detail['pay_status_name'] = "待付尾款";
        }
        if ($detail['car_source'] == 1) {
            $rate = "100%";
        } elseif ($detail['car_source'] == 2) {
            $rate = $detail['three_in_one'] == 1 ? '50%' : '0%';
        }
        $detail['pay_status_name'] = $detail['pay_status_name'] . $rate;
        //付款人
        if ($pay_status > 1) {
            $paymentData = Car::getFirstPaymentBySid($detail['sid']);
            $detail['pay_man'] = $paymentData['emp_name'];
            $detail['pay_time'] = $paymentData['update_time'];
        } else {
            $detail['pay_man'] = "--";
            $detail['pay_time'] = "--";
        }

        //自收成交时间和自收价格
        $self_receive_data = M('self_receive_car')->field('order_id,createtime')->where(['sid' => $detail['sid']])->order('src_id ASC')->limit(1)->find();

        $AuOrder = new AuOrder($self_receive_data['order_id']);
        $self_receive_order = $AuOrder->detail();
        $detail['self_receive_price'] = $self_receive_order['success_price'];
        $detail['self_success_trade_time'] = $self_receive_data['createtime'];
        //成交车商信息
        $dealer = new Dealer($detail['success_dealer_id']);
        $trade_dealer_info = $dealer->detail();
        if (!empty($trade_dealer_info)) {
            $trade_dealer_info = $dealer->get_contact_mobile_byAntNestfind($trade_dealer_info);
        }
        $self_dealer_info = Dealer::get_dealer_info_by_dealer_id($detail['self_receive_dealer_id']);
        $detail['self_dealer_name'] = $self_dealer_info['contact_person'];
        if ($detail['status'] == 3) {
            $detail['dealer_contact_mobile'] = $trade_dealer_info['contact_mobile'];
            $detail['dealer_contact_person'] = $trade_dealer_info['contact_person'];
            $AuOrder = new AuOrder($detail['order_id']);
            $transfer_log = $AuOrder->get_transfer_log(2);
            $man_id = $transfer_log['man_id'];
            if ($man_id) { //如果有提车人
                $TakeMan = new \AuctionCore\CarDealer\TakeMan($detail['success_dealer_id']);
                $succ_takeman = $TakeMan->detail($man_id);
                $detail['take_car_man'] = $succ_takeman['real_name'];
            } else {
                $detail['take_car_man'] = '';
            }
        } elseif ($detail['status'] == 4) { //其它渠道
            $detail['dealer_contact_person'] = $detail['dealer_name'];
            $detail['dealer_contact_mobile'] = $detail['dealer_phone'];
        }
        //车商合手价格
        $detail['bidding_best_price'] = $detail['bid_best_price'] > $detail['bidding_best_price'] ? $detail['bid_best_price'] : $detail['bidding_best_price'];
        $detail['pay_commision'] = get_commision($detail['success_price']);
        $detail['dealer_price'] = sprintf('%.2f', ($detail['bidding_best_price'] - $detail['consult_increase'] + $detail['pay_commision'] + $detail['transfer_fee']));

        $orderFeeData = AuOrder::getOrderFee($detail['order_id']);
        $finalPrice = $orderFeeData['final_price'];
        $detail['final_price'] = $finalPrice; //应收车款

        //平台确认失败备注
        if ($detail['self_type'] == 2) {
            $AuOrder = new AuOrder($detail['order_id']);
            $platform_log = $AuOrder->get_platform_confirm_log(['result' => 3]);
            $detail['platform_confirm_remark'] = $platform_log['remark'];
        }
        //争议信息
        $map = array();
        if ($detail['self_type'] == 3) {
            $map['issue_id'] = ['eq', $detail['issue_id']];
            $dealer_issue = M('dealer_issue')->where($map)->find();
            if ($dealer_issue) {
                $detail['cut_down_price'] = $dealer_issue['cut_down_price'];
                $detail['issue_emp_id'] = $dealer_issue['emp_id'];
                $emp_name = M('employee')->where('emp_id = ' . $detail['issue_emp_id'])->find();
                $detail['emp_name'] = $emp_name['real_name'];
                $detail['issue_remark'] = $dealer_issue['remark'];
                $detail['createtime'] = $dealer_issue['createtime'];
            }
        }
        //复检信息
        if ($detail['car_source'] == 1) {
            $recheck_detail = Recheck::getRecheckInfoBySid($detail['sid']);
            $detail['procedure_checker'] = Employee::user_info_id($recheck_detail['procedure_checker'])['real_name'];
            $detail['condition_checker'] = Employee::user_info_id($recheck_detail['condition_checker'])['real_name'];
            $detail['recheck_time'] = $recheck_detail['recheck_time'];
            $detail['recheck_remark'] = $recheck_detail['remark'];
        }
        $detail['owner_type_name'] = C('OWNER_TYPE_NAME')[$detail['owner_type']];


        if ($detail['status'] == 2) { //如果是已退车
            $refundInfo = RefundLogic::getRefundCarByRefer($src_id, 2);
            $detail['remark_amount_of_car'] = $refundInfo['remark_amount_of_car'];
            $detail['remark_payment'] = $refundInfo['remark_payment'];
            $detail['collection_id'] = $refundInfo['collection_id'];
            $detail['collection_id_car'] = $refundInfo['collection_id_car'];
            $detail['payment_id'] = $refundInfo['payment_id'];
            $detail['back_reason'] = $refundInfo['back_reason'];
        }
        return $detail;
    }


    /**
     * 获取自收车辆和订单详情
     *
     * @param int $src_id
     *
     * @return mixed
     */
    public function self_receive_car_and_order_detail($src_id)
    {
        if (intval($src_id) < 1) return false;
        $cols = 'src.src_id,src.status,src.remark,src.dealer_name,src.dealer_phone,src.trade_price,src.take_car_man,src.issue_id,
                 src.compensate_type,src.compensate,src.back_method,src.self_type,src.reserve_price as current_reserve_price,
                 src.report_type,src.dealtime,src.transfer_fee,src.d_order_id,
                 o.order_id,o.order_no,o.is_consult,o.success_dealer_id,o.bidding_best_price,o.bid_best_price,o.commision,o.transfer_fee as order_transfer_fee,
                 o.consult_increase,o.success_price,o.reserve_price,o.bidding_end_time,o.is_consult,o.company_subsidies,o.confirm_type,o.trade_time,
                 c.car_id,c.sno,c.brand_id,c.series_id,c.model_id,c.car_color,c.emission,c.plate_prefix,c.pointer_mileage,c.plate_prefix,c.plate_suffix,
                 c.car_color,c.composite_state,c.accident_level,c.car_status,c.three_in_one,c.car_source,c.car_no,c.emission,c.au_times,c.is_self_receive,
                 c.self_receive_dealer_id,
                 c.first_reg_date,c.pointer_mileage,c.reg_city,c.vin,c.transfer_limit,c.location_area,c.pay_status,c.first_money,c.tail_money,c.success_price,
                 c.is_self_receive,c.sid,co.seller_name,co.phone as seller_phone,co.comefrom,co.owner_type,co.contact_person,
                 e.real_name as checker_name,e.mobile as checker_phone,co.owner_id';
        //rc.remark_payment,rc.remark_amount_of_car,rc.collection_id,rc.payment_id,rc.back_reason,rc.collection_id,rc.collection_id_car,
        //$map['rc.type'] = ['eq',2]; //1 违约车辆 2 自收车辆
        //->join($prefix . "refund_car as rc ON src.src_id=rc.refer_id")
        $map = array();
        $map['src.src_id'] = ['eq', $src_id];
        $prefix = C('DB_PREFIX');
        $detail = $this->SelfReceiveCarModel->alias('src')->field($cols)
            ->join($prefix . "order as o ON o.order_id = src.d_order_id")
            ->join($prefix . "cars as c ON c.car_id = src.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = c.owner_id")
            ->join($prefix . "employee as e ON e.emp_id = co.checker_id")
            ->where($map)
            ->find();
        $cm = new CarModel();
        $brand = $cm->get_model_by_id($detail['brand_id'], 'brand');
        $series = $cm->get_model_by_id($detail['series_id'], 'series');
        $model = $cm->get_model_by_id($detail['model_id']);
        $detail['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $detail['car_color'] = C('CAR_COLOR.' . $detail['car_color']);
        $detail['emission'] = C('INT_EMISSION_STD.' . $detail['emission']);
        $detail['plate_prefix'] = C('PLATE_PREFIX.' . $detail['plate_prefix']);
        $detail['pointer_mileage'] = formatMileage($detail['pointer_mileage']);
        $detail['transfer_limit_str'] = C('TRANSFER_LIMIT.' . $detail['transfer_limit']);
        $channel = \AuctionCore\Other\Channel::get_full_name_by_id($detail['comefrom']);
        $detail['channel_id'] = $detail['comefrom'];
        $detail['comefrom'] = $channel;
        $addr = new \AuctionCore\Other\Address();
        $detail['first_reg_city'] = $addr->get_name_by_code($detail['reg_city']);
        $detail['location_area_code'] = $detail['location_area']; //所在地code
        $detail['location_area'] = $addr->get_name_by_code($detail['location_area']);
        $detail['reau_times'] = $detail['au_times'] - 1;
        if ($detail['trade_time'] == '0000-00-00 00:00:00') {
            $detail['trade_time'] = '';
        }
        $pay_status = $detail['pay_status'];
        if ($pay_status == 1) {           //待付首款
            $detail['pay_status_name'] = "待付首款";
        } elseif ($pay_status == 2) {     //已付首款
            $detail['pay_status_name'] = "已付首款";
        } elseif ($pay_status == 3) {  //待付尾款
            $detail['pay_status_name'] = "待付尾款";
        }
        if ($detail['car_source'] == 1) {
            $rate = "100%";
        } elseif ($detail['car_source'] == 2) {
            $rate = $detail['three_in_one'] == 1 ? '50%' : '0%';
        }
        $detail['pay_status_name'] = $detail['pay_status_name'] . $rate;
        //付款人
        if ($pay_status > 1) {
            $paymentData = Car::getFirstPaymentBySid($detail['sid']);
            $detail['pay_man'] = $paymentData['emp_name'];
            $detail['pay_time'] = $paymentData['update_time'];
        } else {
            $detail['pay_man'] = "--";
            $detail['pay_time'] = "--";
        }

        //自收成交时间和自收价格
        $self_receive_data = M('self_receive_car')->field('order_id,createtime')->where(['sid' => $detail['sid']])->order('src_id ASC')->limit(1)->find();
        $AuOrder = new AuOrder($self_receive_data['order_id']);

        $self_receive_order = $AuOrder->detail();
        $detail['self_receive_price'] = $self_receive_order['success_price'];
        $detail['self_success_trade_time'] = $self_receive_data['createtime'];
        //成交车商信息
        $dealer = new Dealer($detail['success_dealer_id']);
        $trade_dealer_info = $dealer->detail();
        if (!empty($trade_dealer_info)) {
            $trade_dealer_info = $dealer->get_contact_mobile_byAntNestfind($trade_dealer_info);
        }
        $self_dealer_info = Dealer::get_dealer_info_by_dealer_id($detail['self_receive_dealer_id']);
        $detail['self_dealer_name'] = $self_dealer_info['contact_person'];
        if ($detail['status'] == 3) {
            $detail['dealer_contact_mobile'] = $trade_dealer_info['contact_mobile'];
            $detail['dealer_contact_person'] = $trade_dealer_info['contact_person'];
            $AuOrder = new AuOrder($detail['order_id']);
            $transfer_log = $AuOrder->get_transfer_log(2);
            $man_id = $transfer_log['man_id'];
            if ($man_id) { //如果有提车人
                $TakeMan = new \AuctionCore\CarDealer\TakeMan($detail['success_dealer_id']);
                $succ_takeman = $TakeMan->detail($man_id);
                $detail['take_car_man'] = $succ_takeman['real_name'];
            } else {
                $detail['take_car_man'] = '';
            }
        } elseif ($detail['status'] == 4) { //其它渠道
            $detail['dealer_contact_person'] = $detail['dealer_name'];
            $detail['dealer_contact_mobile'] = $detail['dealer_phone'];
        }
        //车商合手价格
        $detail['bidding_best_price'] = $detail['bid_best_price'] > $detail['bidding_best_price'] ? $detail['bid_best_price'] : $detail['bidding_best_price'];
        $detail['pay_commision'] = get_commision($detail['success_price']);
        $detail['dealer_price'] = sprintf('%.2f', ($detail['bidding_best_price'] - $detail['consult_increase'] + $detail['pay_commision'] + $detail['transfer_fee']));

        //平台确认失败备注
        if ($detail['self_type'] == 2) {
            $AuOrder = new AuOrder($detail['order_id']);
            $platform_log = $AuOrder->get_platform_confirm_log(['result' => 3]);
            $detail['platform_confirm_remark'] = $platform_log['remark'];
        }
        //争议信息
        $map = array();
        if ($detail['self_type'] == 3) {
            $map['issue_id'] = ['eq', $detail['issue_id']];
            $dealer_issue = M('dealer_issue')->where($map)->find();
            if ($dealer_issue) {
                $detail['cut_down_price'] = $dealer_issue['cut_down_price'];
                $detail['issue_emp_id'] = $dealer_issue['emp_id'];
                $emp_name = M('employee')->where('emp_id = ' . $detail['issue_emp_id'])->find();
                $detail['emp_name'] = $emp_name['real_name'];
                $detail['issue_remark'] = $dealer_issue['remark'];
                $detail['createtime'] = $dealer_issue['createtime'];
            }
        }
        //复检信息
        if ($detail['car_source'] == 1) {
            $recheck_detail = Recheck::getRecheckInfoBySid($detail['sid']);
            $detail['procedure_checker'] = Employee::user_info_id($recheck_detail['procedure_checker'])['real_name'];
            $detail['condition_checker'] = Employee::user_info_id($recheck_detail['condition_checker'])['real_name'];
            $detail['recheck_time'] = $recheck_detail['recheck_time'];
            $detail['recheck_remark'] = $recheck_detail['remark'];
        }
        $detail['owner_type_name'] = C('OWNER_TYPE_NAME')[$detail['owner_type']];
        return $detail;
    }

    /**
     * 自收车辆 - 退车流程
     * 我方违约 1 平台责任 判断是否付过车主款？  是---> 应收退款-补偿款  否--->直接补偿车主款
     *        2 车主原因 是否付过车主款？     是---> 应收退款+扣款    否--->不记录
     * 车商违约  判断是否付过车主款？         是---> 应收退款-补偿款   否--->直接补偿车主款
     *
     * @param array $is_pay
     */
    public function is_compensate_Pay($is_pay = [])
    {
        //检测失误 平台责任 ->补偿
        if ($is_pay['back_method'] == 1) {
            if ($is_pay['pay_status'] > 1 && ($is_pay['car_source'] == 1
                    || ($is_pay['car_source'] == 2 && $is_pay['three_in_one'] == 1))
            ) {
                $Params = array(
                    'owner_id' => $is_pay['owner_id'],
                    'order_id' => $is_pay['order_id'],
                    'car_id' => $is_pay['car_id'],
                    'receivable_type' => 1,
                    're_refund_type' => 2,
                    'createtime' => date('Y-m-d h:i:s')
                );
                $res = $this->ReceivableRefund->add_receivable_refund($Params);
            } else {
                $Params = array(
                    'owner_id' => $is_pay['owner_id'],
                    'order_id' => $is_pay['order_id'],
                    'car_id' => $is_pay['car_id'],
                    'compensate_amount' => $is_pay['compensate']
                );
                $res = $this->CarOwnerCompensate->add_car_owner_compensate($Params);
            }
        } else {//车主原因
            //付过车主款
            //应收款=已付金额-扣除金额  插入应收退款表中
            $Params = array(
                'owner_id' => $is_pay['owner_id'],
                'order_id' => $is_pay['order_id'],
                'car_id' => $is_pay['car_id'],
                'receivable_type' => 2,
                're_refund_type' => 2
            );
            $res = $this->ReceivableRefund->add_receivable_refund($Params);
        }
        if ($res === false) {
            \Think\Log::record('自收退车失败！car_id:' . $is_pay['car_id'] . ',emp_id:' . $is_pay['emp_id']);
            return false;
        } else {
            return true;
        }
    }


    /**
     * 新增自收车辆
     *
     * @param $data
     *
     * @return mixed
     */
    public function add_self_receive_car($data)
    {
        if ($data['car_id'] < 1) {
            return false;
        }
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['sid'] = M("cars")->where(['car_id' => $data['car_id']])->getField("sid");
        return $this->SelfReceiveCarModel->add($data);
    }

    /**
     * 更新信息
     *
     * @param $src_id
     * @param $data
     *
     * @return
     */
    public function update_self_receive_car($src_id, $data)
    {
        if ($src_id < 1 || empty($data)) return false;
        $map = array();
        $map['src_id'] = ['eq', $src_id];
        return $this->SelfReceiveCarModel->where($map)->save($data);
    }

    /**
     * 更新信息
     *
     * @param array $data
     * @param array $map
     *
     * @return
     */
    public function update_self_receive_car_data($data = [], $map = [])
    {
        if (empty($map) || empty($data)) return false;
        return $this->SelfReceiveCarModel->where($map)->save($data);
    }

    /**
     * 获取详细信息
     *
     * @param $src_id
     *
     * @return bool|mixed
     */
    public function get_self_receive_car_detail($src_id)
    {
        if (intval($src_id) < 1) return false;
        $map['src_id'] = ['eq', $src_id];
        return $this->SelfReceiveCarModel->where($map)->find();
    }


    /**
     * 获取自收退车详情
     *
     * @param int $order_id
     * @return mixed
     */
    public function get_self_receive_refund($order_id)
    {
        if (intval($order_id) < 1) return false;
        $map['order_id'] = ['eq', $order_id];
        $map['status'] = ['eq', 2];
        $prefix = C('DB_PREFIX');
        $cols = 'src.src_id,src.emp_id as src_emp_id,src.compensate,src.remark as src_remark,src.dealtime,c.self_receive_dealer_id';
        return $this->SelfReceiveCarModel->alias('src')->field($cols)
            ->join($prefix . 'cars as c ON c.car_id = src.car_id')->where($map)->find();
    }

    /**
     * 获取自收其他渠道成交详情
     * @param int $order_id
     * @return mixed
     */
    public function getSelfReceiveOtherChannelDeal($order_id)
    {
        if (intval($order_id) < 1) return false;
        $map['order_id'] = ['eq', $order_id];
        $map['status'] = ['eq', 4];
        $prefix = C('DB_PREFIX');
        $cols = 'src.src_id,src.emp_id as src_emp_id,src.compensate,src.remark as src_remark,src.dealtime,c.self_receive_dealer_id,
                src.trade_price,src.transfer_fee';
        return $this->SelfReceiveCarModel->alias('src')->field($cols)
            ->join($prefix . 'cars as c ON c.car_id = src.car_id')->where($map)->find();
    }

    /**
     * 通过订单号获取其他渠道成交信息
     * @param $otherOrderId
     * @return bool|mixed
     */
    public static function getInfoByOtherOrderId($otherOrderId)
    {
        if (intval($otherOrderId) < 1) return false;
        $map = [
            'status' => 4, //其他渠道成交
            'd_order_id' => $otherOrderId,
        ];
        return M("self_receive_car")->where($map)->find();
    }

}
